<template>
  <div class="app-container">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="佣金规则" name="rule">
        <div class="app-card">
          <!-- 搜索和工具栏 -->
          <div class="table-toolbar">
            <el-form :inline="true" :model="ruleQueryParams" ref="ruleQueryForm">
              <el-form-item label="规则名称">
                <el-input v-model="ruleQueryParams.name" placeholder="请输入规则名称" clearable size="small" />
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="ruleQueryParams.status" placeholder="请选择状态" clearable size="small">
                  <el-option :value="1" label="启用" />
                  <el-option :value="0" label="禁用" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="small" @click="handleRuleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="small" @click="resetRuleQuery">重置</el-button>
              </el-form-item>
            </el-form>
            
            <div>
              <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAddRule">新增</el-button>
            </div>
          </div>
          
          <!-- 表格 -->
          <el-table v-loading="ruleLoading" :data="ruleList" border>
            <el-table-column type="index" label="#" width="50" align="center" />
            <el-table-column prop="name" label="规则名称" min-width="150" />
            <el-table-column label="金额范围" min-width="180">
              <template slot-scope="scope">
                ¥{{ scope.row.minAmount }} - ¥{{ scope.row.maxAmount }}
              </template>
            </el-table-column>
            <el-table-column prop="rate" label="佣金比例" width="120">
              <template slot-scope="scope">
                {{ scope.row.rate }}%
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.status"
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleRuleStatusChange(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column label="操作" width="200" align="center">
              <template slot-scope="scope">
                <el-button type="text" icon="el-icon-edit" @click="handleUpdateRule(scope.row)">编辑</el-button>
                <el-button type="text" icon="el-icon-delete" @click="handleDeleteRule(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="ruleTotal"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="ruleQueryParams.size"
              :current-page="ruleQueryParams.current"
              @size-change="handleRuleSizeChange"
              @current-change="handleRuleCurrentChange"
            />
          </div>
        </div>
        
        <!-- 添加/编辑对话框 -->
        <el-dialog :title="ruleDialogTitle" :visible.sync="ruleDialogVisible" width="600px" append-to-body>
          <el-form ref="ruleForm" :model="ruleForm" :rules="ruleRules" label-width="100px">
            <el-form-item label="规则名称" prop="name">
              <el-input v-model="ruleForm.name" placeholder="请输入规则名称" />
            </el-form-item>
            <el-form-item label="最小金额" prop="minAmount">
              <el-input-number v-model="ruleForm.minAmount" :precision="2" :step="10" :min="0" style="width: 100%" />
            </el-form-item>
            <el-form-item label="最大金额" prop="maxAmount">
              <el-input-number v-model="ruleForm.maxAmount" :precision="2" :step="10" :min="0" style="width: 100%" />
            </el-form-item>
            <div class="form-tip">
              <i class="el-icon-info"></i>
              <span>金额范围不能与现有规则重叠，相邻规则的边界可以相等（例如：0-100与100-200）</span>
            </div>
            <el-form-item label="佣金比例" prop="rate">
              <el-input-number v-model="ruleForm.rate" :precision="2" :step="0.5" :min="0" :max="100" style="width: 100%">
                <template slot="append">%</template>
              </el-input-number>
            </el-form-item>
            <el-form-item label="状态">
              <el-radio-group v-model="ruleForm.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="ruleDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitRuleForm">确 定</el-button>
          </div>
        </el-dialog>
      </el-tab-pane>
      
      <el-tab-pane label="佣金记录" name="commission">
        <div class="app-card">
          <!-- 搜索和工具栏 -->
          <div class="table-toolbar">
            <el-form :inline="true" :model="commissionQueryParams" ref="commissionQueryForm">
              <el-form-item label="团长">
                <el-select v-model="commissionQueryParams.leaderId" placeholder="请选择团长" clearable size="small">
                  <el-option v-for="item in leaderOptions" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="订单编号">
                <el-input v-model="commissionQueryParams.orderNo" placeholder="请输入订单编号" clearable size="small" />
              </el-form-item>
              <el-form-item label="状态">
                <el-select v-model="commissionQueryParams.status" placeholder="请选择状态" clearable size="small">
                  <el-option :value="1" label="已结算" />
                  <el-option :value="0" label="未结算" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="small" @click="handleCommissionQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="small" @click="resetCommissionQuery">重置</el-button>
              </el-form-item>
            </el-form>
            
          
          </div>
          
          <!-- 表格 -->
          <el-table v-loading="commissionLoading" :data="commissionList" border @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" />
            <el-table-column type="index" label="#" width="50" align="center" />
            <el-table-column prop="orderNo" label="订单编号" min-width="180" />
            <el-table-column prop="leaderName" label="团长" width="120" />
            <el-table-column prop="amount" label="佣金金额" width="120">
              <template slot-scope="scope">
                ¥{{ scope.row.amount }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                  {{ scope.row.status === 1 ? '已结算' : '未结算' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column prop="updateTime" label="结算时间" width="180" />
            <el-table-column label="操作" width="120" align="center">
              <template slot-scope="scope">
                <el-button 
                  v-if="scope.row.status === 0" 
                  type="text" 
                  icon="el-icon-check" 
                  @click="handleSettle(scope.row)">结算
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="commissionTotal"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="commissionQueryParams.size"
              :current-page="commissionQueryParams.current"
              @size-change="handleCommissionSizeChange"
              @current-change="handleCommissionCurrentChange"
            />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { 
  listCommissionRules, 
  addCommissionRule, 
  updateCommissionRule, 
  deleteCommissionRule, 
  changeCommissionRuleStatus,
  listCommissions,
  settleCommission,
  settleBatchCommission
} from '@/api/commission'
import { listLeaders } from '@/api/leader'

export default {
  name: 'Commission',
  data() {
    return {
      // 当前激活的标签页
      activeTab: 'rule',
      
      // 佣金规则相关数据
      ruleQueryParams: {
        current: 1,
        size: 10,
        name: '',
        status: ''
      },
      ruleTotal: 0,
      ruleList: [],
      ruleLoading: false,
      ruleDialogTitle: '',
      ruleDialogVisible: false,
      ruleForm: {
        id: undefined,
        name: '',
        minAmount: 0,
        maxAmount: 0,
        rate: 0,
        status: 1
      },
      ruleRules: {
        name: [
          { required: true, message: '请输入规则名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        minAmount: [
          { required: true, message: '请输入最小金额', trigger: 'blur' }
        ],
        maxAmount: [
          { required: true, message: '请输入最大金额', trigger: 'blur' }
        ],
        rate: [
          { required: true, message: '请输入佣金比例', trigger: 'blur' }
        ]
      },
      
      // 佣金记录相关数据
      commissionQueryParams: {
        current: 1,
        size: 10,
        leaderId: '',
        orderNo: '',
        status: ''
      },
      commissionTotal: 0,
      commissionList: [],
      commissionLoading: false,
      leaderOptions: [],
      selectedCommissions: []
    }
  },
  created() {
    this.getRuleList()
    this.getCommissionList()
    this.getLeaderOptions()
  },
  methods: {
    // 获取佣金规则列表
    getRuleList() {
      this.ruleLoading = true
      listCommissionRules(this.ruleQueryParams).then(response => {
        // 如果返回的是数组，直接使用
        if (Array.isArray(response)) {
          this.ruleList = response
          this.ruleTotal = response.length
        } else {
          // 否则尝试获取list和total字段
          this.ruleList = response.list || response.records || []
          this.ruleTotal = response.total || 0
        }
        this.ruleLoading = false
      }).catch(() => {
        this.ruleLoading = false
      })
    },
    // 搜索佣金规则按钮点击事件
    handleRuleQuery() {
      this.ruleQueryParams.current = 1
      this.getRuleList()
    },
    // 重置佣金规则搜索按钮点击事件
    resetRuleQuery() {
      this.$refs.ruleQueryForm.resetFields()
      this.ruleQueryParams.name = ''
      this.ruleQueryParams.status = ''
      this.ruleQueryParams.current = 1
      this.getRuleList()
    },
    // 每页数量改变事件
    handleRuleSizeChange(val) {
      this.ruleQueryParams.size = val
      this.getRuleList()
    },
    // 页码改变事件
    handleRuleCurrentChange(val) {
      this.ruleQueryParams.current = val
      this.getRuleList()
    },
    // 添加佣金规则按钮点击事件
    handleAddRule() {
      this.ruleDialogTitle = '添加佣金规则'
      this.ruleForm = {
        id: undefined,
        name: '',
        minAmount: 0,
        maxAmount: 0,
        rate: 0,
        status: 1
      }
      this.ruleDialogVisible = true
    },
    // 编辑佣金规则按钮点击事件
    handleUpdateRule(row) {
      this.ruleDialogTitle = '编辑佣金规则'
      this.ruleForm = { ...row }
      this.ruleDialogVisible = true
    },
    // 删除佣金规则按钮点击事件
    handleDeleteRule(row) {
      this.$confirm('确认删除该佣金规则吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCommissionRule(row.id).then(() => {
          this.$message.success('删除成功')
          this.getRuleList()
        })
      }).catch(() => {})
    },
    // 佣金规则状态改变事件
    handleRuleStatusChange(row) {
      const text = row.status === 1 ? '启用' : '禁用'
      this.$confirm(`确认${text}该佣金规则吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        changeCommissionRuleStatus(row.id, row.status).then(() => {
          this.$message.success(`${text}成功`)
        })
      }).catch(() => {
        row.status = row.status === 1 ? 0 : 1
      })
    },
    // 佣金规则表单提交事件
    submitRuleForm() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          // 检查最大金额是否大于最小金额
          if (this.ruleForm.maxAmount <= this.ruleForm.minAmount) {
            this.$message.error('最大金额必须大于最小金额')
            return
          }
          
          if (this.ruleForm.id) {
            updateCommissionRule(this.ruleForm).then(() => {
              this.$message.success('修改成功')
              this.ruleDialogVisible = false
              this.getRuleList()
            }).catch(error => {
              console.error('修改佣金规则失败:', error)
            })
          } else {
            addCommissionRule(this.ruleForm).then(() => {
              this.$message.success('添加成功')
              this.ruleDialogVisible = false
              this.getRuleList()
            }).catch(error => {
              console.error('添加佣金规则失败:', error)
            })
          }
        }
      })
    },
    
    // 获取佣金记录列表
    getCommissionList() {
      this.commissionLoading = true
      listCommissions(this.commissionQueryParams).then(response => {
        // 如果返回的是数组，直接使用
        if (Array.isArray(response)) {
          this.commissionList = response
          this.commissionTotal = response.length
        } else {
          // 否则尝试获取list和total字段
          this.commissionList = response.list || response.records || []
          this.commissionTotal = response.total || 0
        }
        this.commissionLoading = false
      }).catch(() => {
        this.commissionLoading = false
      })
    },
    // 获取团长选项
    getLeaderOptions() {
      listLeaders({ size: 100 }).then(response => {
        // 如果返回的是数组，直接使用
        if (Array.isArray(response)) {
          this.leaderOptions = response
        } else {
          this.leaderOptions = response.list || []
        }
      })
    },
    // 搜索佣金记录按钮点击事件
    handleCommissionQuery() {
      this.commissionQueryParams.current = 1
      this.getCommissionList()
    },
    // 重置佣金记录搜索按钮点击事件
    resetCommissionQuery() {
      this.$refs.commissionQueryForm.resetFields()
      this.commissionQueryParams.leaderId = ''
      this.commissionQueryParams.orderNo = ''
      this.commissionQueryParams.status = ''
      this.commissionQueryParams.current = 1
      this.getCommissionList()
    },
    // 每页数量改变事件
    handleCommissionSizeChange(val) {
      this.commissionQueryParams.size = val
      this.getCommissionList()
    },
    // 页码改变事件
    handleCommissionCurrentChange(val) {
      this.commissionQueryParams.current = val
      this.getCommissionList()
    },
    // 表格选择项改变事件
    handleSelectionChange(selection) {
      this.selectedCommissions = selection
    },
    // 结算佣金按钮点击事件
    handleSettle(row) {
      this.$confirm('确认结算该佣金吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        settleCommission(row.id).then(() => {
          this.$message.success('结算成功')
          this.getCommissionList()
        })
      }).catch(() => {})
    },
    // 批量结算佣金按钮点击事件
    handleSettleBatch() {
      if (this.selectedCommissions.length === 0) {
        this.$message.warning('请选择要结算的佣金')
        return
      }
      
      // 过滤出未结算的佣金
      const ids = this.selectedCommissions
        .filter(item => item.status === 0)
        .map(item => item.id)
      
      if (ids.length === 0) {
        this.$message.warning('所选佣金都已结算')
        return
      }
      
      this.$confirm(`确认结算选中的 ${ids.length} 条佣金记录吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        settleBatchCommission(ids).then(response => {
          this.$message.success(`成功结算 ${response.data.successCount} 条佣金记录`)
          this.getCommissionList()
        })
      }).catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.table-toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.form-tip {
  margin: -10px 0 15px 100px;
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
  
  .el-icon-info {
    margin-right: 5px;
    color: #409EFF;
  }
}
</style> 